package com.git.hui.yinshua.biz.user.service;

import com.git.hui.yinshua.biz.rest.models.user.res.UserAddressDto;
import com.git.hui.yinshua.biz.user.dao.domain.UserAddressEntity;
import com.git.hui.yinshua.biz.user.dao.repository.UserAddressRepository;
import com.git.hui.yinshua.biz.user.service.convert.UserConvert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 用户服务
 *
 * @author YiHui
 * @date 2024/6/11
 */
@Service
public class UserAddressService {
    @Autowired
    private UserAddressRepository userAddressRepository;


    /**
     * 查询用户的地址列表
     *
     * @param userId 用户id
     * @return 地址列表
     */
    public List<UserAddressDto> listUserAddress(Integer userId) {
        List<UserAddressEntity> list = userAddressRepository.queryUserAddressList(userId);
        return UserConvert.batchToAddress(list);
    }

    /**
     * 获取用户的默认地址
     *
     * @param userId 用户id
     * @return 默认地址/推荐地址
     */
    public UserAddressDto getDefaultUserAddress(Integer userId) {
        UserAddressEntity userAddress = userAddressRepository.queryMainAddress(userId);
        if (userAddress == null) {
            // 默认地址没有时，选择最新创建的一个返回
            List<UserAddressEntity> list = userAddressRepository.queryUserAddressList(userId);
            if (!CollectionUtils.isEmpty(list)) {
                userAddress = list.get(0);
            }
        }
        if (userAddress != null) {
            return UserConvert.toAddress(userAddress);
        }
        return null;
    }

    /**
     * 新增地址
     *
     * @param userId  用户id
     * @param address 地址
     * @return ture保存成功
     */
    public Boolean addAddress(Integer userId, UserAddressDto address) {
        if (address.getDefaultAddress() == null) {
            address.setDefaultAddress(false);
        }
        if (address.getTag() == null) {
            address.setTag("");
        }
        userAddressRepository.addAddress(userId, address);
        return true;
    }

    /**
     * 更新地址
     *
     * @param userId  用户id
     * @param address 地址
     * @return ture保存成功
     */
    public Boolean updateAddress(Integer userId, UserAddressDto address) {
        userAddressRepository.updateAddress(userId, address);
        return true;
    }

    public boolean deleteAddress(Integer userId, Integer addressId) {
        return userAddressRepository.removeAddress(userId, addressId);
    }

    public boolean updateMainAddress(Integer userId, Integer addressId, Boolean main) {
        userAddressRepository.updateMainAddress(userId, addressId, main);
        return true;
    }
}
